import { createOrder, detail, updateOrder, submitOrder } from 'services/order'
import * as userService from 'services/security/user'
import { mine } from 'services/distributor'
import { routerRedux } from 'dva/router'
import pathToRegexp from 'path-to-regexp'
import { Modal } from 'antd'
import { getRegionCodes } from 'utils/utils'

export default {
  namespace: 'updateOrder',
  state: {
    isUpdate: false,
    currentOrderDetail: {},
    salesmen: [],
    distributors: [],
    listState: '',
    isFormDirty: false,
    isLoading: false
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        const pathname = location.pathname
        if (pathname === '/order/createSalesOrder') {
          dispatch({ type: 'initState', payload: {} })
        }
        const match = pathToRegexp('/order/updateSalesOrder/:id').exec(pathname)
        if (match) {
          let orderId = match[1]
          dispatch({ type: 'setIsUpdate', payload: {} })
          dispatch({
            type: 'getOrderDetail', payload: {
              orderId
            }
          })
        }

        dispatch({ type: 'toSelectDistributors', payload: {} })

        if (!_.isEmpty(location.state)) {
          dispatch({
            type: 'setListState',
            payload: {
              listState: location.state.listState
            }
          })
        }
      })
    }
  },
  effects: {
    * getOrderDetail({
      payload
    }, { select, call, put }) {
      const data = yield call(detail, payload.orderId)
      // 处理省市区数据
      const orderDetail = data.result
      orderDetail.customerRegion = getRegionCodes(orderDetail.customerProvince, orderDetail.customerCity, orderDetail.customerDistrict);
      orderDetail.consigneeRegion = getRegionCodes(orderDetail.consigneeProvince, orderDetail.consigneeCity, orderDetail.consigneeDistrict);
      yield put({
        type: 'getSalesmanByDistributor',
        payload: {
          id: orderDetail.salesDistributorId || ''
        }
      })
      yield put({
        type: 'setCurrentOrderDetail',
        payload: {
          currentOrderDetail: orderDetail
        }
      })
    },

    /**
     * 选择门店
     */
    * toSelectDistributors({
      payload
    }, { select, call, put }) {
      const data = yield call(mine)

      yield put({ type: 'setDistributors', payload: data.list })
      if (data.list.length === 1) {
        const id = data.list[0].id
        yield put({
          type: 'getSalesmanByDistributor',
          payload: {
            id: id
          }
        })
      }
    },

    /**
     * 选择销售员
     */
    * getSalesmanByDistributor({
      payload
    }, { select, call, put }) {
      const { id } = payload
      const data = yield call(userService.byDistributor, id)
      yield put({
        type: 'setSalesmen',
        payload: {
          salesmen: data.result
        }
      })
    },

    /**
     * 选择销售员
     */
    * toSelectSalesman({
      payload
    }, { select, call, put }) {
      const data = yield call(userService.selectSalesmen)
      yield put({
        type: 'setSalesmen',
        payload: {
          salesmen: data.result
        }
      })
    },
    /**
     * 创建意向单
     */
    * createSalesOrder({
      payload
    }, { select, call, put }) {
      const data = yield call(createOrder, payload.salesOrder)
      yield put(routerRedux.push(`/order/updateSalesOrder/${data.result}`))
      yield put({
        type: 'setFormDirty',
        payload: {
          isFormDirty: false
        }
      })
      Modal.success({ title: '意向订单创建成功' })
      yield put({
        type: 'setIsLoading',
        payload: false
      })
    },
    /**
     * 修改意向单
     */
    * updateSalesOrder({
      payload
    }, { select, call, put }) {
      const currentOrderDetail = yield select(({ updateOrder }) => updateOrder.currentOrderDetail)
      yield call(updateOrder, currentOrderDetail.id, payload.salesOrder)
      yield put(routerRedux.push(`/order/updateSalesOrder/${currentOrderDetail.id}`))
      yield put({
        type: 'setFormDirty',
        payload: {
          isFormDirty: false
        }
      })
      Modal.success({ title: '意向订单修改成功' })
      yield put({
        type: 'setIsLoading',
        payload: false
      })
    },
    /**
     * 提交意向单
     */
    * submitSalesOrder({
      payload
    }, { select, call, put }) {
      const currentOrderDetail = yield select(({ updateOrder }) => updateOrder.currentOrderDetail)
      yield call(submitOrder, currentOrderDetail.id, currentOrderDetail.version)
      yield put(routerRedux.push(`/orderList/myOrder`))
      Modal.success({ title: '意向订单下单成功' })
      yield put({
        type: 'setIsLoading',
        payload: false
      })
    }
  },
  reducers: {
    initState(state, { payload }) {
      return {
        ...state,
        ...payload,
        isUpdate: false,
        currentOrderDetail: {}
      }
    },
    setDistributors(state, { payload }) {
      state.distributors = payload
      if (payload.length === 1) {
        state.currentOrderDetail.salesDistributorId = payload[0].id
      }

      return {
        ...state
      }
    },
    setSalesmen(state, { payload }) {
      return {
        ...state,
        ...payload,
        salesmen: payload.salesmen
      }
    },
    setIsUpdate(state, { payload }) {
      return {
        ...state,
        ...payload,
        isUpdate: true
      }
    },
    setCurrentOrderDetail(state, { payload }) {
      return {
        ...state,
        ...payload,
        currentOrderDetail: payload.currentOrderDetail
      }
    },
    setListState(state, { payload }) {
      return {
        ...state,
        ...payload,
        listState: payload.listState
      }
    },
    setFormDirty(state, { payload }) {
      return {
        ...state,
        ...payload,
        isFormDirty: payload.isFormDirty
      }
    },
    setIsLoading(state, { payload }) {
      return {
        ...state,
        ...payload,
        isLoading: payload
      }
    }
  }
}
